﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.Web;
using SecurityClient;

namespace SecurityModule.Workflows
{
    class WFPostHomeForgotPassword : SimpleWorkflow
    {
        public WFPostHomeForgotPassword()
        {
            Verb = "POST";
            Path = "/Home/ForgotPassword";
        }
        public override void PreProcessImplementation(HttpContext context)
        {
            // No pre-processing
        }

        public override void PostProcessImplementation(HttpContext context)
        {
            if (context.Response.StatusCode != 200 && context.Response.StatusCode != 302) return;
            var email = string.Empty;
            try
            {
                // Read form fields
                email = context.Request.Form["Email"];

                var security = new SecurityServiceProxy();
                //Generate EmailVerificationToken
                var result = security.RequestEmailVerification("", email); // no need for ClientCode

                if (result.Success)
                {
                    var helper =
                        new EmailHelper(
                            GetEmailTemplatePath("PasswordResetRequest"),
                            ConfigurationManager.AppSettings["RootUrl"],
                            ConfigurationManager.AppSettings["SupportEmail"],
                            ConfigurationManager.AppSettings["AppName"]
                            );
                    var emailBody = helper.GetEmailBody(new {token = result.TokenId});
                    try
                    {
                        // send reset password email
                        helper.SendEmail(email, "Reset Password", emailBody);
                    }
                    catch (Exception exp)
                    {
                        // sending email failed
                        EventLog.WriteEntry("SecModule",
                                            string.Format(
                                                "Failed sending email to reset password for user {0}, error: {1}", email,
                                                exp.Message), EventLogEntryType.Error);
                    }
                }
                else
                {
                    EventLog.WriteEntry("SecModule", string.Format("Failed acquiring password reset token for user {0}", email), EventLogEntryType.Error);                    
                }
            }
            catch (Exception exp)
            {
                // preparing email failed
                EventLog.WriteEntry("SecModule", string.Format("Failed preparing email to invite user {0}, error: {1}", email, exp.Message), EventLogEntryType.Error);
            }
        }
    }
}
